/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import com.sun.org.apache.bcel.internal.generic.ARRAYLENGTH;
import com.toedter.calendar.JDateChooser;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.xml.bind.JAXBException;
import views.*;
import models.*;
import org.xml.sax.SAXException;
import utils.AddToXml;
import utils.LoadXml;
import utils.Message;
import utils.SearchUtils;
import utils.Validation;
import utils.EditToXml;

/**
 *
 * @author plato
 */
public class XmlController {
    //[import] bien private cua view va model

    private MainView mainView = new MainView();
    private Add addView = new Add();
    private Edit editView = new Edit();
    private Validation validation = new Validation();
    private Students students; // after browse
    private ArrayList<Student> resultToForm;// save object to display in form
    private JTable tbToForm;
    private LoadXml loadXml;// de tinh tu luc load yeu cau user ko change xml file sau khi load
    private int flagLoad = 0;
    private String comboSelected = "First Name";
    private String path;
    private int valueIndex;
    private Student studentGetted; // Student get from select in jtable
    private Student studentFromEditForm;

    public void init() {
        mainView.setVisible(true);
        // AddView Controller listener
        addView.addAddListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                try {
                    path = mainView.getPathToFie();
                    // get Date of JDateChooser and other
                    String id = addView.getId().getText();
                    String firstName = addView.getFirstName().getText();
                    String lastName = addView.getLastName().getText();
                    String address = addView.getAddress().getText();
                    String age = addView.getAge().getText();
                    String note = addView.getNote().getText();
                    Date dob = addView.getJDateChooser().getDate();
                    // validate 
                    loadXml = new LoadXml(mainView.getPathToFie());
                    Students ss1 = (Students) loadXml.getStudents();
                    ArrayList listStu = (ArrayList) ss1.getListStudent();
                    boolean check = new Validation().checkErrorAddForm(id, listStu, firstName, lastName, address, age, note, dob, addView);
                    // after validate , result false or true -> continue accomplish or show error if errors
                    if (check == true) {
                        try {
                            Student student = new Student(Integer.parseInt(id), firstName, lastName, address, Integer.parseInt(age), dob.toString(), note);
                            // Add data to xml
                            AddToXml addToXml = new AddToXml();
                            addToXml.addStudentToXml(path, student);
                            // Display success
                            addView.displayMessage(Message.ADD_SUCCESS);
                            // Load again to form
                            try {
                                loadXml = new LoadXml(mainView.getPathToFie());
                                Students students = (Students) loadXml.getStudents();
                                loadToView(students);
                            } catch (IOException ex) {
                                Logger.getLogger(XmlController.class.getName()).log(Level.SEVERE, null, ex);
                            }

                        } catch (JAXBException ex) {
                            Logger.getLogger(XmlController.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    } else {
                        JOptionPane.showMessageDialog(addView,
                                "Have error when input data!",
                                "ERROR",
                                JOptionPane.ERROR_MESSAGE);
                    }
                } catch (IOException ex) {
                    Logger.getLogger(XmlController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        // clear button in Add form
        addView.clearAddListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                addView.getFirstName().setText("");
                addView.getLastName().setText("");
                addView.getAddress().setText("");
                addView.getAge().setText("");
                addView.getJDateChooser().setDate(new Date());
                addView.getNote().setText("");
            }
        });
        // browseListener
        mainView.browseAddListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                JFileChooser file = new JFileChooser();
                int result = file.showOpenDialog(mainView);
                if (result == JFileChooser.APPROVE_OPTION) {
                    // check is XML file    
                    String path = file.getSelectedFile().getAbsolutePath();
                    if (validation.validateXML(path)) {
                        mainView.setPathToFile(file.getSelectedFile().getAbsolutePath());

                        try {
                            loadXml = new LoadXml(mainView.getPathToFie());
                            //load All Student from xml file
                            students = loadXml.getStudents();
                            loadToView(students);
                            flagLoad = 1;
                            //enable some button if load xml is success
                            mainView.getBtnSearch().setEnabled(true);
                            mainView.getBtnAdd().setEnabled(true);
                            mainView.getBtnEdit().setEnabled(true);
                            mainView.getBtnDelete().setEnabled(true);
                        } catch (IOException ex) {
                            Logger.getLogger(XmlController.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (Exception ex) {
                            mainView.displayXmlError("FILE XML HAVE ERROR");
                        }

                    } else {
                        mainView.displayXmlError(Message.ERROR_XML);
                    }

                }
            }
        });
        // AddListener
        mainView.addAddListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                mainView.setEnabled(false);
                addView.setVisible(true);
                addView.getMainView(mainView);
            }
        });
        // ExitListener
        mainView.exitAddListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                System.exit(0);
            }
        });
        // comboListener
        mainView.addComboListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                JComboBox cb = (JComboBox) evt.getSource();
                comboSelected = (String) cb.getSelectedItem();

            }
        });
        // SearchListener
        mainView.addSearchListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                try {
                    // neu load success thi moi search
                    loadXml = new LoadXml(mainView.getPathToFie());
                    ArrayList<Student> listStudent = new ArrayList<>();
                    Students students = new Students();
                    //load All Student from xml file
                    listStudent = (ArrayList<Student>) loadXml.getStudents().getListStudent();
                    if (flagLoad == 1) {
                        resultToForm = new SearchUtils().searchInList(comboSelected, listStudent, mainView.getInputSearch());
                        students.setListStudent(resultToForm);
                        loadToView(students);
                    } else {
                        mainView.displayXmlError("Need load xml file");
                    }
                } catch (IOException ex) {
                    Logger.getLogger(XmlController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        //Load EditListener
        mainView.addEditListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                // get index from view. Only select 1
                int[] selectedRows = mainView.getJtableMain().getSelectedRows();
                if (selectedRows.length == 0 || selectedRows.length > 1) {
                    JOptionPane.showMessageDialog(mainView,
                            Message.HAVE_SELECT_ONE_TO_EDIT,
                            "Select warning",
                            JOptionPane.WARNING_MESSAGE);
                } else {
                    try {

                        // display edit form
                        mainView.setEnabled(false);
                        editView.setVisible(true);
                        editView.getMainView(mainView);
                        //mainView.displayXmlError(selectedRows[0] + "");// check index row selected
                        // get selected object Student from index column index row
                        valueIndex = (int) mainView.getJtableMain().getValueAt(selectedRows[0], 0); // get comlumn value from selected
                        studentGetted = new Student();
                        LoadXml loadXml = new LoadXml(path);
                        students = loadXml.getStudents();
                        List<Student> listStu = loadXml.getStudents().getListStudent();
                        for (int i = 0; i < listStu.size(); i++) {
                            if (students.getListStudent().get(i).getId() == valueIndex) {
                                studentGetted = students.getListStudent().get(i);
                                break;
                            }
                        }
                        // Load student to Edit form. Parse date if need
                        editView.setId(studentGetted.getId() + "");
                        editView.setFirstName(studentGetted.getFirstName());
                        editView.setLastName(studentGetted.getLastName());
                        editView.setAddress(studentGetted.getAddress());
                        editView.setAge(studentGetted.getAge());
                        //mainView.displayXmlError(studentGetted.getDob());
                        editView.setNote(studentGetted.getNote());
                        //DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
                        String dateInString = studentGetted.getDob();
                        Date date;
                        try {
                            date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(dateInString);
                            editView.setJDateChooser(date);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                    } catch (IOException ex) {
                        Logger.getLogger(XmlController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
            }
        });
        // edit in to xml and load to jtable again
        editView.editAddListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                //edit xml
                EditToXml editToXml = new EditToXml();
                String id = editView.getId().getText();
                String firstName = editView.getFirstName().getText();
                String lastName = editView.getLastName().getText();
                String address = editView.getAddress().getText();
                String age = editView.getAge().getText();
                String dob="";
                if(editView.getJDateChooser().getDate()!=null)  {
                dob = editView.getJDateChooser().getDate().toString();
                }
                String note = editView.getNote().getText();
                ArrayList<Student> listStu = (ArrayList<Student>) students.getListStudent();
                boolean check = new Validation().checkErrorAddForm(id, listStu, firstName, lastName, address, age, note, editView.getJDateChooser().getDate(), editView);
                if (check) {
                    studentFromEditForm = new Student(Integer.parseInt(id), firstName, lastName, address, Integer.parseInt(age), dob, note);
                    editToXml.editStudentToXml(mainView.getPathToFie(), studentFromEditForm);
                    editView.displayMessage(Message.EDIT_SUCCESS);
                    // load jtable again
                    try {
                        loadXml = new LoadXml(mainView.getPathToFie());
                        loadToView(loadXml.getStudents());
                    } catch (IOException ex) {
                        Logger.getLogger(XmlController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    JOptionPane.showMessageDialog(editView,
                            "Have error when edit data!",
                            "ERROR",
                            JOptionPane.ERROR_MESSAGE);
                }

            }
        });
        editView.undoAddListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                editView.setId(studentGetted.getId() + "");
                editView.setFirstName(studentGetted.getFirstName());
                editView.setLastName(studentGetted.getLastName());
                editView.setAddress(studentGetted.getAddress());
                editView.setAge(studentGetted.getAge());
                //mainView.displayXmlError(studentGetted.getDob());
                editView.setNote(studentGetted.getNote());
            }
        });
        //        DeleteListener
        mainView.addDeleteListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {

                int[] selectedRows = mainView.getJtableMain().getSelectedRows();
                int[] valueIndexs = new int[selectedRows.length];
                if (selectedRows.length > 0) {
                    int n = JOptionPane.showConfirmDialog(
                            mainView,
                            "Do you delete ?",
                            "Delete confirm",
                            JOptionPane.YES_NO_OPTION);
                    if (n == 0) {
                        for (int i = 0; i < selectedRows.length; i++) {
                            valueIndexs[i] = (Integer) mainView.getJtableMain().getValueAt(selectedRows[i], 0);
                        }
                        EditToXml delete = new EditToXml();
                        try {
                            delete.deleteStudentToXml(mainView.getPathToFie(), valueIndexs);
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                        // load jtable again
                        try {
                            loadXml = new LoadXml(mainView.getPathToFie());

                            loadToView(loadXml.getStudents());
                        } catch (IOException ex) {
                            Logger.getLogger(XmlController.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                } else {
                    mainView.displayXmlError(Message.DONT_HAVE_ROW_TO_DELETE);
                }
            }
        });

    }// init
    //[import] thuc thi listener
    //[import] constructor truyen vao view va model va listener
    // load to View

    public void loadToView(Students students) {
        try {
            LoadXml loadXml = new LoadXml(mainView.getPathToFie());
            Object[][] rows = new Object[students.getListStudent().size()][8];
            Object[] columnNames = {"STT", "First Name", "Last Name", "Address", "Age", "Date Of Birth", "Note", "Delete?"};
            for (int i = 0; i < students.getListStudent().size(); i++) {
                Student student = students.getListStudent().get(i);
                rows[i][0] = student.getId();
                rows[i][1] = student.getFirstName();
                rows[i][2] = student.getLastName();
                rows[i][3] = student.getAddress();
                rows[i][4] = student.getAge();
                rows[i][5] = student.getDob();
                rows[i][6] = student.getNote();
                rows[i][7] = "";
            }

            StudentModel model = new StudentModel(rows, columnNames, (ArrayList<Student>) students.getListStudent());
            // set data for JTable
            tbToForm = mainView.getJtableMain();
            tbToForm.setModel(model);
            // Add checkbox for column 7
            JCheckBox comboBox = new JCheckBox();
            TableCellEditor editor = new DefaultCellEditor(comboBox);
            tbToForm.getColumnModel().getColumn(7).setCellEditor(editor); //[NOTE]

        } catch (IOException ex) {
            Logger.getLogger(XmlController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @SuppressWarnings("CallToThreadDumpStack")
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            new XmlController().init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
